package com.tiny.core.service.impl;

import com.tiny.core.controller.UserController;
import com.tiny.core.dao.UserDao;
import com.tiny.core.domain.User;
import com.tiny.core.domain.WeekReport;
import com.tiny.core.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by connie_gnauhsil on 2018/5/30.
 */
@Service
public class UserServiceImpl implements UserService {

    private final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    @Qualifier("userDao")
    private UserDao userDao;

    public User findUserByName(String userName) {
        System.out.println(userDao.findByName(userName) + "  == userName");
        return userDao.findByName(userName);
    }

    @Transactional
    public List<User> userList(){
        return userDao.userList();
    }

    @Transactional
    public User userRedis(String key){

        ValueOperations<String, User> operations = redisTemplate.opsForValue();

        // 缓存存在
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            User user = operations.get(key);

            logger.info("CityServiceImpl.findCityById() : 从缓存中获取了城市 >> " + user.toString());
            return user;
        }

        User user = userDao.findByName(key);

        operations.set(key, user, 10, TimeUnit.SECONDS);
        logger.info("CityServiceImpl.findCityById() : 城市插入缓存 >> " + user.toString());

        return user;

    }


    public void add(User user){
        userDao.add(user);
    }

}
